// 函数组件
import React, { useState, useEffect } from 'react';
import "./css/OperationShop.less"
import type { ColumnsType } from 'antd/es/table';
import { Table, Switch, Button, Modal, Input, message, ConfigProvider, Select, Form, InputNumber } from 'antd';
import zh_CN from 'antd/es/locale/zh_CN';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { useNavigate, useLocation } from "react-router-dom";
import { showZoneShop, baseUrl, modPosition, delShop } from '../../../api/operationApi';
import { use } from 'echarts';


interface DataType {
    goodsId: number,
    goodsImg: string,
    goodsName: string,
    goodsSerNum: number,
    goodsPriceRange: number,
    categoryName: string,
    goodsSell: number,
    state: number,
    location: number,
}



// 表单布局
const layout = {
    labelCol: {
        span: 6,
    },
    wrapperCol: {
        span: 16,
    },
};
// 表单验证
const validateMessages = {
    required: '${label}必填',
    types: {
        number: '${label}必须是数值',
    }
};


function OperationShop() {
    const navigate = useNavigate();
    const [form] = Form.useForm();

    const columns: ColumnsType<DataType> = [
        {
            title: '序号',
            dataIndex: 'goodsId',
            align: 'center',
            width: '15%'
        },
        {
            title: '商品图片',
            dataIndex: 'goodsImg',
            align: 'center',
            render: (value, record, index) => {
                return (
                    <img src={baseUrl + value} width={50} height={50} />
                )
            }
        },

        {
            title: '商品名称',
            dataIndex: 'goodsName',
            align: 'center',
        },
        {
            title: '货号',
            dataIndex: 'goodsSerNum',
            align: 'center',
        },
        {
            title: '价格',
            dataIndex: 'goodsPriceRange',
            align: 'center',
        },

        {
            title: '分类',
            dataIndex: 'categoryName',
            align: 'center',
        },
        {
            title: '销量',
            dataIndex: 'goodsSell',
            align: 'center',
        },
        {
            title: '位置',
            dataIndex: 'location',
            align: 'center',
        },
        {
            title: '是否上架',
            dataIndex: 'state',
            align: 'center',
            render: (value, record, index) => {
                return (
                    <Switch checked={value} />
                )
            }
        },
        {
            title: '操作',
            dataIndex: 'operation',
            align: 'center',
            width: '16%',
            render: (value, record) => (
                <div>
                    <button className='edit' onClick={() => clickPosition(record)}>位置</button>
                    <button className='del' onClick={() => clickDel(record)}>移除</button>
                </div>
            ),
        },
    ];

    const [currentPage, setCurrentPage] = useState<number>(1) // 当前页
    const [pageSize, setPageSize] = useState<number>(10)  // 一页条数
    const [count, setCount] = useState<number>() // 总数
    const [sortWay, setSortWay] = useState<string>()  // 排序方式


    // 表格数据
    const [data, setData] = useState<DataType[]>([])
    // 1、表格渲染数据
    useEffect(() => {
        getData(currentPage, pageSize, sortWay)
    }, [currentPage, pageSize])

    // 1-1 删除当前页最后一项，页码改变
    useEffect(() => {
        if (currentPage > 1 && data.length === 0) {
            setCurrentPage(currentPage - 1)
        }
    }, [data])

    // 1-2 获取数据
    // 接收传递的专区id
    const location = useLocation()
    async function getData(currentPage: number, pageSize: number, sortWay?: string) {
        let res = await showZoneShop(
            {
                "currentPage": currentPage,
                "pageSize": pageSize,
                "sortWay": sortWay,
                "tsaId": location.state.tsaId
            }
        )
        console.log('专区商品',res);

        let data = res.data.vyyGoods.map((item: any) => {
            let obj: any = {}
            for (const key in item) {
                if (typeof item[key] === 'object') {
                    for (const val in item[key]) {
                        obj[val] = item[key][val]
                    }
                } else {
                    obj[key] = item[key]
                }
            }
            return item = obj
        })
        console.log('商品', data);

        // let setId:number[] = []
        let newData = data.map((item: any) => {
            if (!item.location) {
                item['location'] = '待设'
            }
            return item
        })

        setCount(res.data.total)
        setData(newData)

    }

    // 1-3 改变页码
    const getPageContent = (currentPage: number, pageSize: number) => {
        setCurrentPage(currentPage)
        setPageSize(pageSize)
    }


    // 下拉选项
    const selectOption: {}[] = [
        { value: '按序号顺序', label: '按序号顺序' },
        { value: '按序号倒序', label: '按序号倒序' },
    ]

    // 2、选择排序方式
    const changeSort = (value: string): void => {
        console.log('%c' + '=========>', 'color: #886CE4;font-weight:bolder', 'value', value);
        setSortWay(value)
        getData(currentPage, pageSize, value)
        message.success('排序成功')
    }


    // 3、点击添加,跳转页面
    const clickAdd = () => {
        navigate("/home/operations/addShop", {
            state: {  // 必须传state 这个名字
                tsaId: location.state.tsaId
            }
        })
    }


    // 4、位置弹框部分
    const [isPositionOpen, setIsPositionOpen] = useState<boolean>(false)
    const [id, setId] = useState<number>()
    const [position, setPositon] = useState<number>()
    const clickPosition = (item: DataType): void => {
        if (typeof (item.location) == 'string') {
            // setPositon(0)
            form.resetFields()
            form.setFieldsValue({
                location: ''
            })
        } else {
            form.resetFields()
            setPositon(item.location)
            form.setFieldsValue({
                location: item.location
            })
        }
        setId(item.goodsId)
        setIsPositionOpen(true)
    }

    // 设置位置
    const onFinish = async (values: any) => {
        console.log("values", values);
        console.log('%c' + '=========>', 'color: #886CE4;font-weight:bolder', 'id', id);
        // 遍历是否有相同的location 
        let isExist: boolean = false
        try {
            data.forEach((item: DataType) => {
                if (item.location == values.location) {
                    isExist = true
                    throw ('同一专区的商品位置不可相同')
                }
            })
        } catch (error) {
            console.log('error', error);
        }

        if (isExist) {
            message.warning('同一专区商品不能处于相同位置')
        } else {
            let res = await modPosition(
                {
                    "goodsId": id,
                    "location": values.location,
                    "tsaId": location.state.tsaId
                }
            )
            setPositon(values.location)
            message.success('设置成功')
            setIsPositionOpen(false)
            getData(currentPage, pageSize, sortWay)
        }

    };

    // 5、移除
    const { confirm } = Modal;
    const clickDel = (item: DataType) => {
        console.log('item111', item);
        confirm({
            title: '确定移除该商品吗?',
            icon: <ExclamationCircleFilled />,
            content: '删除之后就没了哦~',
            async onOk() {
                await delShop({
                    "goodsId": item.goodsId,
                    "tsaId": location.state.tsaId
                })
                getData(currentPage, pageSize, sortWay)
                console.log('%c' + '=========>', 'color: #886CE4;font-weight:bolder', 'data', data);
                message.success('删除成功')
            },
            onCancel() {
                message.warning('取消操作')
            },
        });
    }


    return (
        <div className='OperationShop'>
            {/* 头部 */}
            <div className='page-top'>
                {/*左边标题  */}
                <div className='page-title'>
                    <p>专区管理</p>
                </div>
            </div>

            {/* 内容区 */}
            <div className='page-context'>
                {/* 数据表格部分 */}
                <div className='data-list'>
                    <div className='list-title'>
                        <p>商品列表</p>
                        <div className='list-operation'>
                            <div className='operation-one'>
                                <p>排序方式</p>
                                <Select
                                    className='select-shelf'
                                    placeholder="排序方式"
                                    style={{ width: 140 }}
                                    allowClear
                                    options={selectOption}
                                    onChange={changeSort}
                                />
                            </div>
                            <div>
                                <button className='add' onClick={clickAdd}>添加商品</button>
                            </div>
                        </div>
                    </div>

                    {/* 表格部分 */}
                    <ConfigProvider locale={zh_CN}>
                        <Table
                            columns={columns}
                            dataSource={data}
                            scroll={{ y: 444 }}
                            rowKey={item => item.goodsId}
                            pagination={{
                                position: ['bottomCenter'],
                                total: count,
                                pageSize: pageSize,
                                onChange: getPageContent,
                                defaultPageSize: 10,
                                pageSizeOptions: [3, 5, 10, 15],
                                showQuickJumper: true,
                                showSizeChanger: true,
                            }}
                        />
                    </ConfigProvider>


                </div>

            </div>

            {/* 弹框 */}
            <Modal centered={true} forceRender width={460} title='设置位置' open={isPositionOpen} footer={null} onCancel={() => setIsPositionOpen(false)} >
                <Form
                    {...layout}
                    name="shop-form"
                    onFinish={onFinish}
                    validateMessages={validateMessages}
                    form={form}
                >
                    <Form.Item
                        name='location'
                        label="设置位置"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                        initialValue={position}
                    >
                        <InputNumber min={1} max={10} />
                    </Form.Item>
                    <Form.Item
                        wrapperCol={{
                            ...layout.wrapperCol,
                            offset: 5,
                        }}
                    >
                        <p className='explain'>说明：位置序号越大,排序越靠前</p>
                    </Form.Item>

                    <Form.Item
                        wrapperCol={{
                            ...layout.wrapperCol,
                            offset: 8,
                        }}
                    >
                        <Button type="primary" htmlType="submit" className='confirm-btn' >确定</Button>
                        <Button type="primary" onClick={() => setIsPositionOpen(false)} ghost>取消</Button>
                    </Form.Item>
                </Form>
            </Modal>


        </div>
    )
}

export default OperationShop